<?php
namespace AliPay;

/**
 *
 * @author lovebing <i@lovebing.org>
 */
class Base extends BaseAbstract {

    protected $md5Key = '';
    protected $apiURL = 'https://mapi.alipay.com/gateway.do';
    protected $mainParams = array(
        'service' => '',
        'partner' => '',
        '_input_charset' => 'utf-8',
        'sign_type' => 'MD5',
        'sign' => '',
        'notify_url' => '',
        'return_url' => '',
        'error_notify_url' => ''
    );
    protected $businessParams = array();
    private $params = array();

    public function go() {
        $url = $this->getRedirectURL();
        if ($url != '') {
            header('Location: ' . $url);
        }
    }

    protected function buildParams() {
        $this->params = array_merge($this->mainParams, $this->businessParams);
        foreach ($this->params as $k => $v) {
            if (trim($v) == '') {
                unset($this->params[$k]);
            }
        }
        $this->params['sign'] = $this->sign($this->params);
    }

    protected function sign($params) {
        unset($params['sign']);
        unset($params['sign_type']);
        ksort($params);
        $str = array();
        foreach ($params as $k => $v) {
            $str[] = $k . '=' . $v;
        }
        return md5(implode('&', $str) . $this->md5Key);
    }

    public function getRedirectURL() {
        $this->buildParams();
        return $this->apiURL . '?' . http_build_query($this->params);
    }

}

?>
